/**
 * 优惠券缓存管理工具
 * 提供统一的优惠券数据缓存机制，支持10分钟有效期
 * 支持多租户org_id隔离
 */

import { API_CONFIG } from '@/api/config.js'

const CACHE_DURATION = 10 * 60 * 1000 // 10分钟的毫秒数
const GLOBAL_CACHE_KEY = 'global_coupons_cache'

export default {
  /**
   * 检查缓存是否有效
   * @param {string} cacheKey 缓存键
   * @returns {boolean} 是否有效
   */
  isCacheValid(cacheKey) {
    const cacheData = uni.getStorageSync(cacheKey)
    if (!cacheData || !cacheData.timestamp) {
      return false
    }
    const now = Date.now()
    const cacheTime = cacheData.timestamp
    return (now - cacheTime) < CACHE_DURATION
  },

  /**
   * 获取缓存数据
   * @param {string} cacheKey 缓存键
   * @returns {any} 缓存的数据
   */
  getCacheData(cacheKey) {
    const cacheData = uni.getStorageSync(cacheKey)
    return cacheData ? cacheData.data : null
  },

  /**
   * 设置缓存数据
   * @param {string} cacheKey 缓存键
   * @param {any} data 要缓存的数据
   */
  setCacheData(cacheKey, data) {
    const cacheData = {
      data: data,
      timestamp: Date.now()
    }
    uni.setStorageSync(cacheKey, cacheData)
    console.log(`优惠券缓存数据已保存: ${cacheKey}, 有效期至: ${new Date(Date.now() + CACHE_DURATION).toLocaleString()}`)
  },

  /**
   * 获取优惠券缓存
   * @param {string} status 优惠券状态 (all, 0, 1, 2)
   * @param {string} orgId 组织ID，用于多租户隔离
   * @param {string} userId 用户ID
   * @returns {array|null} 优惠券数据数组或null
   */
  getCouponCache(status, orgId = API_CONFIG.ORG_ID, userId) {
    const cacheKey = `coupons_${status}_org_${orgId}_user_${userId}`
    if (this.isCacheValid(cacheKey)) {
      console.log(`使用缓存的${status}优惠券数据 (org_id: ${orgId}, user_id: ${userId})`)
      return this.getCacheData(cacheKey)
    }
    return null
  },

  /**
   * 设置优惠券缓存
   * @param {string} status 优惠券状态 (all, 0, 1, 2)
   * @param {array} data 优惠券数据数组
   * @param {string} orgId 组织ID，用于多租户隔离
   * @param {string} userId 用户ID
   */
  setCouponCache(status, data, orgId = API_CONFIG.ORG_ID, userId) {
    const cacheKey = `coupons_${status}_org_${orgId}_user_${userId}`
    this.setCacheData(cacheKey, data)
    
    // 同时更新全局优惠券缓存，供其他页面使用
    const globalCacheKey = `${GLOBAL_CACHE_KEY}_org_${orgId}_user_${userId}`
    let globalCache = this.getCacheData(globalCacheKey) || {}
    globalCache[status] = {
      data: data,
      timestamp: Date.now()
    }
    this.setCacheData(globalCacheKey, globalCache)
  },

  /**
   * 从全局缓存获取优惠券数据
   * @param {string} status 优惠券状态
   * @param {string} orgId 组织ID，用于多租户隔离
   * @param {string} userId 用户ID
   * @returns {array|null} 优惠券数据数组或null
   */
  getGlobalCouponCache(status, orgId = API_CONFIG.ORG_ID, userId) {
    const globalCacheKey = `${GLOBAL_CACHE_KEY}_org_${orgId}_user_${userId}`
    const globalCache = this.getCacheData(globalCacheKey)
    if (globalCache && globalCache[status] && 
        (Date.now() - globalCache[status].timestamp) < CACHE_DURATION) {
      console.log(`从全局缓存获取${status}优惠券数据 (org_id: ${orgId}, user_id: ${userId})`)
      return globalCache[status].data
    }
    return null
  },

  /**
   * 清除指定状态的优惠券缓存
   * @param {string} status 优惠券状态
   * @param {string} orgId 组织ID，用于多租户隔离
   * @param {string} userId 用户ID
   */
  clearCouponCache(status, orgId = API_CONFIG.ORG_ID, userId) {
    const cacheKey = `coupons_${status}_org_${orgId}_user_${userId}`
    uni.removeStorageSync(cacheKey)
    
    // 同时清除全局缓存中的对应数据
    const globalCacheKey = `${GLOBAL_CACHE_KEY}_org_${orgId}_user_${userId}`
    let globalCache = this.getCacheData(globalCacheKey) || {}
    if (globalCache[status]) {
      delete globalCache[status]
      this.setCacheData(globalCacheKey, globalCache)
    }
    console.log(`已清除${status}优惠券缓存 (org_id: ${orgId}, user_id: ${userId})`)
  },

  /**
   * 清除所有优惠券缓存
   * @param {string} orgId 组织ID，用于多租户隔离
   * @param {string} userId 用户ID
   */
  clearAllCouponCache(orgId = API_CONFIG.ORG_ID, userId) {
    const statuses = ['all', '0', '1', '2']
    statuses.forEach(status => {
      const cacheKey = `coupons_${status}_org_${orgId}_user_${userId}`
      uni.removeStorageSync(cacheKey)
    })
    const globalCacheKey = `${GLOBAL_CACHE_KEY}_org_${orgId}_user_${userId}`
    uni.removeStorageSync(globalCacheKey)
    console.log(`已清除所有优惠券缓存 (org_id: ${orgId}, user_id: ${userId})`)
  },

  /**
   * 获取缓存状态信息
   * @param {string} orgId 组织ID，用于多租户隔离
   * @param {string} userId 用户ID
   * @returns {object} 缓存状态信息
   */
  getCacheStatus(orgId = API_CONFIG.ORG_ID, userId) {
    const statuses = ['all', '0', '1', '2']
    const status = {}
    
    statuses.forEach(type => {
      const cacheKey = `coupons_${type}_org_${orgId}_user_${userId}`
      const isValid = this.isCacheValid(cacheKey)
      const data = this.getCacheData(cacheKey)
      status[type] = {
        valid: isValid,
        count: data ? data.length : 0,
        timestamp: isValid ? new Date(uni.getStorageSync(cacheKey).timestamp).toLocaleString() : null
      }
    })
    
    return status
  },

  /**
   * 清除指定组织的所有用户优惠券缓存
   * @param {string} orgId 组织ID
   */
  clearAllCouponCacheForOrg(orgId) {
    try {
      const storageInfo = uni.getStorageInfoSync()
      const keys = storageInfo.keys || []
      
      // 查找所有匹配的优惠券缓存键
      const couponCacheKeys = keys.filter(key => {
        return key.includes(`_org_${orgId}_user_`) && (key.startsWith('coupons_') || key.startsWith('global_coupons_cache_'))
      })
      
      // 删除所有匹配的缓存
      couponCacheKeys.forEach(key => {
        uni.removeStorageSync(key)
      })
      
      console.log(`已清除组织 ${orgId} 的所有优惠券缓存，共 ${couponCacheKeys.length} 个缓存项`)
    } catch (error) {
      console.error('清除组织优惠券缓存失败:', error)
    }
  }
}